<template>
  <div class="aggregation-login">
    <div class="login-container">
      <div class="login-header">
        <h2 class="title">聚合码项目管理系统</h2>
        <p class="subtitle">多角色统一登录平台</p>
      </div>

      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <!-- 隐藏角色选择，系统自动识别 -->
        <el-form-item prop="userType" style="display: none;">
          <el-input v-model="loginForm.userType" type="hidden"></el-input>
        </el-form-item>

        <!-- 账号输入 -->
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            type="text"
            auto-complete="off"
            placeholder="请输入账号"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            :type="passwordVisible ? 'text' : 'password'"
            auto-complete="off"
            placeholder="请输入密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            <i
              slot="suffix"
              :class="passwordVisible ? 'el-icon-view' : 'el-icon-hide'"
              class="password-icon"
              @click="passwordVisible = !passwordVisible"
            ></i>
          </el-input>
        </el-form-item>

        <!-- 短信验证码（忘记密码时显示） -->
        <el-form-item prop="code" v-if="showSmsCode">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="请输入短信验证码"
            style="width: 60%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <el-button
            :disabled="smsCountdown > 0"
            @click="sendSmsCode"
            class="sms-btn"
          >
            {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '获取验证码' }}
          </el-button>
        </el-form-item>

        <!-- 记住密码 -->
        <el-checkbox v-model="loginForm.rememberMe" class="remember-checkbox">
          记住密码
        </el-checkbox>

        <!-- 登录按钮 -->
        <el-form-item class="login-btn-item">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            class="login-btn"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">{{ loginButtonText }}</span>
            <span v-else>登录中...</span>
          </el-button>
        </el-form-item>

        <!-- 忘记密码链接 -->
        <div class="forgot-password">
          <el-link type="primary" @click="toggleForgotPassword">
            {{ showSmsCode ? '返回登录' : '忘记密码？' }}
          </el-link>
        </div>
      </el-form>

      <!-- 系统说明 -->
      <div class="role-description">
        <el-card shadow="never" class="description-card">
          <div slot="header" class="card-header">
            <span>系统说明</span>
          </div>
          <div class="role-list">
            <div class="role-item">
              <i class="el-icon-info"></i>
              <span>系统将根据您的账号自动识别角色权限</span>
            </div>
            <div class="role-item">
              <i class="el-icon-user"></i>
              <span>支持总公司、区域代理、业务员、商家等多种角色</span>
            </div>
            <div class="role-item">
              <i class="el-icon-lock"></i>
              <span>请使用您的账号和密码登录</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部版权 -->
    <div class="login-footer">
      <span>Copyright © 2024 聚合管理系统 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { aggregationLogin, forgetPassword, sendSmsCode, validateSmsCode, getCurrentUser } from '@/api/aggregation'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: 'AggregationLogin',
  data() {
    return {
      loginForm: {
        userType: null, // 不设置默认值，由后端返回
        userName: '', // 默认账号
        passWord: '', // 默认密码
        code: '',
        oldPassWord: '',
        rememberMe: false
      },
      loginRules: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        code: [
          { required: false, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      loading: false,
      passwordVisible: false,
      showSmsCode: false,
      smsCountdown: 0,
      countdownTimer: null
    }
  },
  computed: {
    loginButtonText() {
      return this.showSmsCode ? '重置密码' : '登录'
    }
  },
  created() {
    this.getCookie()

    // 检查是否已经有token但没有userType，如果有就清除token
    const token = this.$store.getters.token
    const userType = this.$store.getters.userType

    if (token && !userType) {
      Logger.log('检测到无效的token状态，清除token')
      // 使用 FedLogOut 前端登出，避免触发后端 API 调用
      this.$store.dispatch('FedLogOut').catch(() => {
        // 忽略错误，因为可能没有有效的 token
      })
    } else if (token && userType) {
      Logger.log('检测到有效的登录状态，准备跳转到首页')
      // 如果有有效的登录状态，路由守卫会自动处理跳转
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
  methods: {


    // 切换忘记密码模式
    toggleForgotPassword() {
      this.showSmsCode = !this.showSmsCode
      this.loginForm.code = ''
      if (this.showSmsCode) {
        this.loginRules.passWord[0].required = false
        this.loginRules.code[0].required = true
      } else {
        this.loginRules.passWord[0].required = true
        this.loginRules.code[0].required = false
      }
    },

    // 发送短信验证码
    async sendSmsCode() {
      if (!this.loginForm.userName) {
        this.$message.error('请先输入手机号')
        return
      }

      if (!/^1[3-9]\d{9}$/.test(this.loginForm.userName)) {
        this.$message.error('请输入正确的手机号')
        return
      }

      try {
        await sendSmsCode(this.loginForm.userName)
        this.$message.success('验证码已发送')
        this.startCountdown()
      } catch (error) {
        this.$message.error('验证码发送失败')
      }
    },

    // 开始倒计时
    startCountdown() {
      this.smsCountdown = 60
      this.countdownTimer = setInterval(() => {
        this.smsCountdown--
        if (this.smsCountdown <= 0) {
          clearInterval(this.countdownTimer)
          this.countdownTimer = null
        }
      }, 1000)
    },

    // 获取Cookie中的登录信息
    getCookie() {
      const userName = Cookies.get('aggregation_username')
      const passWord = Cookies.get('aggregation_password')
      const rememberMe = Cookies.get('aggregation_rememberMe')
      const userType = Cookies.get('aggregation_userType')

      if (userName && passWord && rememberMe === 'true') {
        this.loginForm = {
          ...this.loginForm,
          userName: userName,
          passWord: decrypt(passWord),
          rememberMe: true,
          userType: userType ? parseInt(userType) : 5
        }
      }
    },

    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true

          // 处理记住密码
          if (this.loginForm.rememberMe) {
            Cookies.set('aggregation_username', this.loginForm.userName, { expires: 30 })
            Cookies.set('aggregation_password', encrypt(this.loginForm.passWord), { expires: 30 })
            Cookies.set('aggregation_rememberMe', this.loginForm.rememberMe, { expires: 30 })
            Cookies.set('aggregation_userType', this.loginForm.userType, { expires: 30 })
          } else {
            Cookies.remove('aggregation_username')
            Cookies.remove('aggregation_password')
            Cookies.remove('aggregation_rememberMe')
            Cookies.remove('aggregation_userType')
          }

          // 执行登录或重置密码
          if (this.showSmsCode) {
            this.handleResetPassword()
          } else {
            this.handleNormalLogin()
          }
        }
      })
    },

    // 正常登录
    async handleNormalLogin() {
      try {
        // 只发送手机号和密码，不发送userType
        const loginData = {
          userName: this.loginForm.userName,
          passWord: this.loginForm.passWord
        }

        // 新接口返回格式: {code: 0, msg: "操作成功", data: {...}}
        const response = await aggregationLogin(loginData)

        if (response.code === 0) {
          // 保存token和用户信息
          this.$store.commit('SET_TOKEN', response.data.token)
          this.$store.commit('SET_USER_TYPE', response.data.type)
          this.$store.commit('SET_USER_PHONE', this.loginForm.userName)

          // 设置用户ID - 从API返回中获取真实用户ID
          const userId = response.data.id
          if (userId) {
            this.$store.commit('SET_ID', userId)
            Logger.log('✅ 登录成功，获取到真实用户ID:', userId)
          } else {
            Logger.log('⚠️ 登录API未返回用户ID，使用手机号作为fallback')
            this.$store.commit('SET_ID', this.loginForm.userName)
          }

          Logger.log('=== 登录成功，用户信息已保存 ===')
          Logger.log('用户ID:', userId)
          Logger.log('用户类型:', response.data.type)
          Logger.log('用户名称:', response.data.name)
          Logger.log('用户手机:', response.data.phone || this.loginForm.userName)
          Logger.log('完整返回数据:', response.data)

          // 如果登录接口返回了头像，立即设置头像
          if (response.data.avatar && response.data.avatar.trim()) {
            this.$store.commit('SET_AVATAR', response.data.avatar)
            Logger.log('✅ 登录接口返回头像，已设置:', response.data.avatar)
          } else if (response.data.name) {
            // 设置用户名（如果有）
            this.$store.commit('SET_NAME', response.data.name)
          }

          // 立即获取用户详情信息并保存到缓存
          await this.loadUserDetail(userId)

          // 显示登录成功消息
          this.$message.success('登录成功！')

          // 清除旧路由状态（防止使用上一个账号的路由）
          Logger.log('清除旧路由状态...')
          await this.$store.dispatch('permission/ResetRoutes')
          Logger.log('✅ 旧路由状态已清除')

          // 先生成动态路由，再进行跳转（避免404）
          Logger.log('开始生成动态路由...')
          await this.$store.dispatch('GenerateRoutes')
          Logger.log('✅ 动态路由生成完成')

          // 根据用户类型跳转到对应的首页
          const roleDashboardMap = {
            5: '/admin/dashboard',    // 总公司
            4: '/agent/dashboard',    // 区域代理
            2: '/salesman/dashboard', // 业务员
            3: '/merchant/dashboard'  // 商家
          }
          const redirectPath = roleDashboardMap[response.data.type] || '/admin/dashboard'
          Logger.log('跳转到:', redirectPath)

          // 使用replace避免返回到登录页
          this.$router.replace({ path: redirectPath })
        } else {
          this.$message.error(response.msg || '登录失败')
        }
      } catch (error) {
        Logger.error('登录错误:', error)
        this.$message.error('登录失败，请检查网络连接或联系管理员')
      } finally {
        this.loading = false
      }
    },

    // 获取用户详情信息（使用新的便捷接口）
    async loadUserDetail(userId) {
      try {
        Logger.log('开始获取用户详情信息...')
        Logger.log('使用getCurrentUser接口，无需传参')

        const response = await getCurrentUser() // 使用新的便捷接口，无需传参
        Logger.log('用户详情API响应:', response.data)

        // 新接口返回格式: {code: 0, msg: "操作成功", data: {...}}
        if (response.code === 0 && response.data) {
          const userDetail = response.data
          Logger.log('✅ 获取用户详情成功:', userDetail)

          // 保存用户详情到Vuex store
          this.$store.commit('SET_USER_INFO', userDetail)

          // 如果API返回了真实的用户ID，更新store中的ID
          if (userDetail.id && userDetail.id !== this.$store.state.user.id) {
            this.$store.commit('SET_ID', userDetail.id)
            Logger.log('✅ 更新用户ID为:', userDetail.id)
          }

          // 如果接口返回了头像，更新store中的头像
          if (userDetail.avatar && userDetail.avatar.trim()) {
            this.$store.commit('SET_AVATAR', userDetail.avatar)
            Logger.log('✅ 用户详情接口返回头像，已更新:', userDetail.avatar)
          }

          // 更新用户名（如果有）
          if (userDetail.name || userDetail.userName) {
            this.$store.commit('SET_NAME', userDetail.userName || userDetail.name)
          }

          // 保存到localStorage作为缓存
          localStorage.setItem('userDetail', JSON.stringify(userDetail))
          Logger.log('✅ 用户详情已保存到localStorage缓存')

          return userDetail
        } else {
          Logger.log('⚠️ 用户详情API返回失败:', response.data)
          return null
        }
      } catch (error) {
        Logger.error('❌ 获取用户详情失败:', error)
        return null
      }
    },

    // 重置密码
    async handleResetPassword() {
      try {
        const response = await forgetPassword(this.loginForm)

        // 新接口返回格式: {code: 0, msg: "操作成功", data: {...}}
        if (response.code === 0) {
          this.$message.success('密码重置成功，请使用新密码登录')
          this.showSmsCode = false
          this.loginForm.passWord = ''
          this.loginForm.code = ''
        } else {
          this.$message.error(response.msg || '密码重置失败')
        }
      } catch (error) {
        this.$message.error('密码重置失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.aggregation-login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 450px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  padding: 40px;
  margin-bottom: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;

  .title {
    font-size: 28px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 8px 0;
  }

  .subtitle {
    font-size: 14px;
    color: #7f8c8d;
    margin: 0;
  }
}

.login-form {
  .role-select {
    width: 100%;
    margin-bottom: 20px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }

  .password-icon {
    cursor: pointer;
    color: #c0c4cc;
    font-size: 16px;

    &:hover {
      color: #409eff;
    }
  }

  .sms-btn {
    width: 38%;
    height: 38px;
    margin-left: 2%;
  }

  .remember-checkbox {
    margin: 0 0 20px 0;
    color: #606266;
  }

  .login-btn-item {
    margin-bottom: 15px;
  }

  .login-btn {
    width: 100%;
    height: 45px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 6px;
  }
}

.forgot-password {
  text-align: center;
  margin-bottom: 20px;
}

.role-description {
  margin-top: 20px;

  .description-card {
    border: none;
    box-shadow: none;
    background: rgba(248, 249, 250, 0.8);

    .card-header {
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;
    }

    .role-list {
      .role-item {
        margin-bottom: 8px;
        font-size: 13px;

        .role-name {
          font-weight: 500;
          color: #34495e;
        }

        .role-desc {
          color: #7f8c8d;
        }
      }
    }
  }
}

.login-footer {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    margin: 10px;
    padding: 30px 20px;
  }

  .login-header .title {
    font-size: 24px;
  }
}
</style>
